package com.lhoverc.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lhoverc.pojo.Result;
import com.lhoverc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import static com.lhoverc.constant.ErrorConstant.NOT_LOGIN;
import static com.lhoverc.constant.ErrorConstant.NO_PERMISSION;

/**
 * @Author: LiCheng
 * @CreateTime: 2025-04-21
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Component
public class LoginCheckIntercepter implements HandlerInterceptor {
    //目标资源方法运行之前运行，返回true：放行，返回false：截断
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求的url
        String url = request.getRequestURL().toString();
        log.info("请求的url：{}", url);

        //2、判断请求url中是否包含login，如果包含放行
        if (url.contains("/login") || url.contains("/register") || url.contains("/getReCaptcha") || url.contains("/forgetPassword")) {
            log.info("登录操作，放行...");
            return true;
        }
        if(url.contains("/check")||url.contains("/pass")||url.contains("/res")){
            log.info("访客操作，放行...");
            return true;
        }

        //3、获取请求头中的jwt令牌（token）
        String jwt = request.getHeader("token");

        //4、判断令牌是否存在，如果不存在，返回错误结果（未登录）
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空，返回未登录信息");
            Result error = Result.error(NOT_LOGIN);
            log.info("result:{}", error);
            //手动转换 对象--json------------->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            log.info("notLogin:{}", notLogin);
            response.getWriter().write(notLogin);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //5、解析token，如果解析失败，返回错误结果（未登录）
        try {
            Claims claims = JwtUtil.parseJWT(jwt);
            //判断是否越权访问
            if (url.contains("/admin") && claims.get("status", Integer.class) != 1) {
                Result error = Result.error(NO_PERMISSION);
                //手动转换 对象--json------------->阿里巴巴fastJSON
                String notLogin = JSONObject.toJSONString(error);
                response.getWriter().write(notLogin);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回未登录错误信息");
            Result error = Result.error(NOT_LOGIN);
            //手动转换 对象--json------------->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //6、放行
        log.info("令牌合法，放行");
        return true;
    }

    //目标资源方方法运行后运行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //视图渲染完毕后运行，最后运行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
